package com.akkainaction.router.group.actor.managemsg;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.dispatch.OnComplete;
import akka.pattern.Patterns;
import akka.routing.*;
import akka.util.Timeout;
import com.typesafe.config.ConfigFactory;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class TestManageMsg {

    public static void main(String[] args) throws InterruptedException {
        ActorSystem system = ActorSystem.create("sys", ConfigFactory.load("managemsg-router.conf"));
        ActorRef masterRouterActor = system.actorOf(Props.create(RouterActor.class), "routerActor");
        //新增一个routee
        ActorRef workActor = system.actorOf(Props.create(WorkActor.class), "workActor");
        masterRouterActor.tell(new AddRoutee(new ActorRefRoutee(workActor)), ActorRef.noSender());

        //查看router下面的routee
        Timeout timeout = new Timeout(Duration.create(10, "seconds"));
        Future<Object> fu = Patterns.ask(masterRouterActor, GetRoutees.getInstance(), timeout);
        fu.onComplete(new OnComplete<Object>() {
            @Override
            public void onComplete(Throwable err, Object result) throws Throwable {
                Routees rs = (Routees) result;
                List<Routee> listRoutees = rs.getRoutees();
                for (Routee r : listRoutees) {
                    System.out.println("routee:" + r);
                }
            }
        }, system.dispatcher());

        //为了阻塞程序不执行下面代码,因为代码是异步执行
        TimeUnit.SECONDS.sleep(10);
        System.out.println("-----------分割线--------------");
        //删除routee
        masterRouterActor.tell(new RemoveRoutee(new ActorRefRoutee(workActor)), ActorRef.noSender());

        //查看router下面的routee
        fu = Patterns.ask(masterRouterActor, GetRoutees.getInstance(), timeout);
        fu.onComplete(new OnComplete<Object>() {
            @Override
            public void onComplete(Throwable err, Object result) throws Throwable {
                Routees rs = (Routees) result;
                List<Routee> listRoutees = rs.getRoutees();
                for (Routee r : listRoutees) {
                    System.out.println("routee:" + r);
                }
            }
        }, system.dispatcher());
    }
}
